﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scheduledscheduling
{
    public class Sugar
    {
        public static SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString,//连接符字串
            DbType = DbType.SqlServer,//数据库类型
            IsAutoCloseConnection = true //不设成true要手动close
        },
             db =>
             {
                 //调试SQL事件
                 db.Aop.OnLogExecuting = (sql, pars) =>
                  {
                      var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars);
                      if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
                      {
                          Console.ForegroundColor = ConsoleColor.Blue;
                          Console.WriteLine($"==============新增/修改操作==============");
                      }
                      if (sql.StartsWith("DELETE"))
                      {
                          Console.ForegroundColor = ConsoleColor.Red;
                          Console.WriteLine($"==============删除操作==============");
                      }
                      if (sql.StartsWith("SELECT"))
                      {
                          Console.ForegroundColor = ConsoleColor.Green;
                          Console.WriteLine($"==============查询操作==============");
                      }
                     //ToSqlExplain 在标题6中有完整代码
                     //Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql
                     Console.ForegroundColor = ConsoleColor.White;
                  };
                 db.Aop.OnLogExecuted = (sql, pars) =>
                 {
                     //执行时间超过1秒
                     if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                     {
                         //代码CS文件名
                         var fileName = db.Ado.SqlStackTrace.FirstFileName;
                         //代码行数
                         var fileLine = db.Ado.SqlStackTrace.FirstLine;
                         //方法名
                         var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
                         //sql
                         var exesql = sql;
                         //参数
                         var sqlpars = pars;
                         //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息
                     }
                 };
             });
    }
}
